package main

import (
	"fmt"
	"math/rand"
	"sync"
)

// 要求：
// ● 使用多个goroutine并发搜索数组
// ● 使用channel或其他同步机制通知找到元素
// ● 找到元素时立即停止其他goroutine

func main() {
	arr := make([]int, 0)
	for i := 0; i < 10000; i++ {
		arr = append(arr, rand.Intn(10000))
	}

	target := arr[564]
	fmt.Println("target is: ", target)
	ch := make(chan bool)
	wg := sync.WaitGroup{}

	for i := 0; i < 100; i++ {
		wg.Add(1)
		start := i * 100
		end := start + 100
		if i == 99 {
			end = 10000
		}
		go search(arr, ch, target, start, end, &wg)
	}
	wg.Wait()
	close(ch)
}

func search(arr []int, ch chan bool, target, start, end int, wg *sync.WaitGroup) {
	defer wg.Done()
	for i := start; i < end; i++ {
		if arr[i] == target {
			fmt.Println("find! index is", i, "value is", arr[i])
			ch <- true
			return
		}
	}

	go func() {
		select {
		case <-ch:
			return
		}
	}()
}
